import http from '../../utils/https';

// 首页逻辑代码
Page({
  // 页面数据
  data: {
    // 最新公告信息
    latestNotice: {
      id: '',
      title: '暂无公告',
      time: ''
    },
    activityList: [],
    loading: false,
    // 添加Banner数据
    bannerList: []
  },
  // 页面加载时执行
  onLoad: function (options) {
    console.log('首页加载完成');
    // 调用获取Banner数据的方法
    this.getBannerList();
    this.loadTop5Activities();
  },
  // 修改后的获取前5条活动数据方法
  async loadTop5Activities() {
    this.setData({ loading: true });
    try {
      // 使用封装的http工具，与activity页面保持一致
      const res = await http.get('activity/activity/publishedList');

      if (res.code === 200) {
        // 格式化日期并取前5条
        const formattedList = res.data.map(item => ({
          ...item,
          time: this.formatDate(item.submitDate)
        })).slice(0, 5);

        console.log('格式化后的活动列表:', formattedList);
        this.setData({ activityList: formattedList });
      } else {
        wx.showToast({ title: '加载失败', icon: 'error' });
      }
    } catch (error) {
      console.error('活动加载错误:', error);
      wx.showToast({ title: '网络异常', icon: 'error' });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 日期格式化方法
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },
  // 获取Banner数据
  getBannerList: function() {
    const app = getApp();
    // 从Storage中获取token
    const token = wx.getStorageSync('token');
    console.log('获取到的token:', token);
  
    wx.request({
      url: app.globalData.baseUrl + '/system/bannermanagement/list',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token // 添加Token认证
      },
      success: (res) => {
        console.log('Banner请求成功结果:', res);
        if (res.data.code === 200) {
          // 修正数据访问路径
          console.log('获取到的Banner数据:', res.data.rows);
          this.setData({
            bannerList: res.data.rows
          });
        } else {
          wx.showToast({
            title: '获取轮播图失败: ' + res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('Banner请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete: () => {
        console.log('Banner请求完成');
      }
    });
  },
  // 获取最新公告数据
  getLatestNotice: function() {
    const app = getApp();
    const token = wx.getStorageSync('token');

    if (!token) {
      console.log('未登录，无法获取公告数据');
      return;
    }

    wx.request({
      url: app.globalData.baseUrl + '/property/notice/list',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        console.log('获取公告列表成功:', res.data);
        if (res.data.code === 200 && res.data.rows && res.data.rows.length > 0) {
          // 按发布日期降序排序，取第一条
          const sortedList = res.data.rows.sort((a, b) =>
            new Date(b.publishTime) - new Date(a.publishTime)
          );
          const latestNotice = sortedList[0];

          // 格式化日期
          const publishDate = new Date(latestNotice.publishTime);
          const formattedDate = `${publishDate.getFullYear()}-${String(publishDate.getMonth() + 1).padStart(2, '0')}-${String(publishDate.getDate()).padStart(2, '0')} ${String(publishDate.getHours()).padStart(2, '0')}:${String(publishDate.getMinutes()).padStart(2, '0')}`;

          this.setData({
            latestNotice: {
              id: latestNotice.id,
              title: latestNotice.noticeTitle,
              time: formattedDate
            }
          });
        } else {
          console.log('暂无公告数据');
          this.setData({
            latestNotice: {
              id: '',
              title: '暂无公告',
              time: ''
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取公告列表失败:', err);
        this.setData({
          latestNotice: {
            id: '',
            title: '获取公告失败',
            time: ''
          }
        });
      }
    });
  },
  // 点击紧急通知卡片 - 跳转到公告详情页
  goToNoticeDetail: function() {
    const { latestNotice } = this.data;

    if (!latestNotice.id) {
      wx.showToast({
        title: '暂无公告详情',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: `/service/pages/announcementDetails/announcementDetails?id=${latestNotice.id}`
    });
  },
  // 点击手机开门功能
  goToPhoneOpen: function() {
    wx.navigateTo({
      url: '/service/pages/opendoor/opendoor',
    })
    // wx.navigateTo({
    //   url: '/pages/phone-open/phone-open'
    // });
  },
  // 点击生活缴费功能
  goToPayment: function() {
    wx.navigateTo({
      url: '/service/pages/payment/payment'
    });
  },
  // 点击维修上报功能
  goToRepair: function() {
    wx.navigateTo({
      url: '/service/pages/repairReport/repairReport'
    });
  },
  // 点击访客邀请功能
  goToVisitor: function() {
    wx.navigateTo({
      url: '/service/pages/visitor/visitor'
    });
  },
  // 点击社区活动列表项 - 跳转到活动详情页
  goToActivityDetail: function(e) {
    const activityId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/index/pages/activity-detail/activity-detail?id=' + activityId
    });
  },

  //点击社区活动查看全部-跳转到活动列表页
  goToActivityList:function(){
    wx.navigateTo({
      url: '/service/pages/activity/activity',
    })
  },

  // 点击轮播图 - 跳转到轮播图详情页
  goToBannerDetail: function(e) {
    const banner = e.currentTarget.dataset.banner;
    console.log('点击的轮播图:', banner);

    // 将轮播图数据传递到详情页
    wx.navigateTo({
      url: '/index/pages/banner-detail/banner-detail?id=' + banner.id + '&name=' + encodeURIComponent(banner.name) + '&remark=' + encodeURIComponent(banner.remark) + '&image=' + encodeURIComponent(banner.bannerThumb)
    });
  }
});